package com.shushan.util;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.android.permission.FloatPermissionUtil;
import com.shushan.base.ActivityStackManager;
import com.shushan.base.BaseActivity;
import com.shushan.base.Constants;
import com.shushan.home.TabHomeActivity;
import com.shushan.lockscreen.GamesFloatWindow;
import com.shushan.lockscreen.GamesWindowManager;
import com.shushan.lockscreen.LockScreenWindowManager;
import com.shushan.lockscreen.bean.AppInfo;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.permission.OpenUsageActivity;
import com.shushan.permission.OpenWindowActivity;
import com.shushan.receiver.LockFreeGameReceiver;
import com.shushan.receiver.SleepFreeReceiver;
import com.shushan.receiver.SleepLockReceiver;
import com.shushan.receiver.TimeMgFreeReceiver;
import com.shushan.receiver.TimeMgLockReceiver;
import com.shushan.receiver.UnlockChildReceiver;
import com.shushan.service.ForegroundRTAService;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.ui.FloatToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;

import static android.content.Context.ALARM_SERVICE;

/**
 * @ClassName: ControlUtil
 * @Desciption: 控制工具类
 * @author: yichaohua
 * @date: 2018-06-21
 */
public class ControlUtil {

    private static final String TAG = "ControlUtil";

    public static void lockChildPsw(Context context, int time) {
        if(time <= 0){
            return;
        }

        FloatToast.makeText(context,"远程锁屏已经开启").show();

        SharedPreferencesUtils.setBooleanDate(Constants.LOCK_CHILD_PSW_SHAREPREFERS_KEY,true);

        boolean isGamesAvailable = GamesWindowManager.isIsGamesAvailable();
        boolean isRtaAlive = SystemUtils.isServiceWork(context,Constants.FOREGROUND_RTA_SERVICE_CLASS_NAME);
        Log.i(TAG,"isGamesAvailable=" + isGamesAvailable + " isRtaAlive=" + isRtaAlive);

        if(isGamesAvailable || isRtaAlive){
            GamesWindowManager.removeGamesFloatWindow(BabyApplication.getInstance());

            Intent intent = new Intent();
            intent.putExtra(Constants.CLEAR_WARN_DIALOG_KEY,Constants.CLEAR_WARN_DIALOG_KEY);
            intent.setAction(Constants.FREE_WARN__RECEIVER_ACTION);
            context.sendBroadcast(intent);

            GamesWindowManager.removeGamesFloatWindow(BabyApplication.getInstance());
            Intent intent1 = new Intent(context,ForegroundRTAService.class);
            context.stopService(intent1);

            ToolUtils.cancelLockAlarm(context);
        }

        LockScreenWindowManager.createLockFloatWindow(context);

        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,0,
                new Intent(context, UnlockChildReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        long atTimeInMillis1 = System.currentTimeMillis() + 1000*60*time;
        am.setExact(AlarmManager.RTC_WAKEUP,atTimeInMillis1,pendingIntent1);

        noticeLockChild(context,1,time);
    }

    public static void unLockChildPsw(Context mContext,int time) {
        FloatToast.makeText(mContext,"远程锁屏已关闭").show();

        SharedPreferencesUtils.setBooleanDate(Constants.LOCK_CHILD_PSW_SHAREPREFERS_KEY,false);

        AlarmManager am = (AlarmManager)mContext.getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(mContext,0,
                new Intent(mContext, UnlockChildReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(pendingIntent1);

        noticeLockChild(mContext,0,time);
    }

    public static void freeGame(Context context, String tempPsw, int time) {
        if(TextUtils.isEmpty(tempPsw) || time <= 0){
            return;
        }

        FloatToast.makeText(context,"临时密码已经开启").show();

        SharedPreferencesUtils.setStringDate(Constants.FREE_GAME_PSW_SHAREPREFERS_KEY,tempPsw);

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("startTimeMillis",System.currentTimeMillis());
            jsonObject.put("time",time);
            SharedPreferencesUtils.setStringDate(Constants.FREE_GAME_START_JSON_SHAREPREFERS_KEY,jsonObject.toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }

        noticePswGames(context,1,time,tempPsw);
    }

    public static void lockFreeGame(Context context, String tempPsw, int time) {
        FloatToast.makeText(context,"临时密码已关闭").show();

        SharedPreferencesUtils.setStringDate(Constants.FREE_GAME_PSW_SHAREPREFERS_KEY,"");
        SharedPreferencesUtils.setStringDate(Constants.FREE_GAME_START_JSON_SHAREPREFERS_KEY,"");

        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,0,
                new Intent(context, LockFreeGameReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(pendingIntent1);

        boolean isGamesAvailable = GamesWindowManager.isIsGamesAvailable();
        boolean isRtaAlive = SystemUtils.isServiceWork(context,Constants.FOREGROUND_RTA_SERVICE_CLASS_NAME);
        GamesFloatWindow gamesFloatWindow = GamesWindowManager.getGamesFloatWindow();
        Log.i(TAG,"isGamesAvailable=" + isGamesAvailable + " isRtaAlive=" + isRtaAlive);

        if((isGamesAvailable || isRtaAlive) && (gamesFloatWindow != null && (gamesFloatWindow.getPaperId() <= 0))){
            GamesWindowManager.removeGamesFloatWindow(BabyApplication.getInstance());

            Intent intent = new Intent();
            intent.putExtra(Constants.CLEAR_WARN_DIALOG_KEY,Constants.CLEAR_WARN_DIALOG_KEY);
            intent.setAction(Constants.FREE_WARN__RECEIVER_ACTION);
            context.sendBroadcast(intent);

            GamesWindowManager.removeGamesFloatWindow(BabyApplication.getInstance());
            Intent intent1 = new Intent(context,ForegroundRTAService.class);
            context.stopService(intent1);

            ToolUtils.cancelLockAlarm(context);

            SystemUtils.sendForegActivity(context,TabHomeActivity.class);
        }

        noticePswGames(context,0,time,tempPsw);
    }

    public static void gotoPswGamesFloat(Context mContext) {
        if(SystemUtils.checkUsagePermission(mContext)){
            String json = SharedPreferencesUtils.getStringDate(Constants.FREE_GAME_START_JSON_SHAREPREFERS_KEY);
            if(!TextUtils.isEmpty(json)){
                try {
                    JSONObject jsonObject = new JSONObject(json);
                    long startTimeMillis = jsonObject.optLong("startTimeMillis",0);
                    int time = jsonObject.optInt("time",0);

                    Log.i(TAG,"gotoGamesFloat startTimeMillis=" + startTimeMillis + " time=" + time);

                    if(time > 0){
                        BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
                        if(baseActivity != null){
                            baseActivity.setAllowBack(true);
                        }
                        ActivityStackManager.getActivityStackManager().popAllActivity();

                        GamesWindowManager.createGamesFloatWindow(mContext);

                        ToolUtils.setLockAlarm(mContext, time);

                        AlarmManager am = (AlarmManager)mContext.getSystemService(ALARM_SERVICE);
                        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(mContext,0,
                                new Intent(mContext, LockFreeGameReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
                        long atTimeInMillis1 = System.currentTimeMillis() + 1000*60*time;
                        am.setExact(AlarmManager.RTC_WAKEUP,atTimeInMillis1,pendingIntent1);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }else {
            FloatToast.makeText(mContext,"发现您尚未开启“有权查看应用使用情况”，请开启后再试").show();
        }
    }

    public static void noticeLockChild(Context context,int lockType,int time){
        UrlParse urlParse = new UrlCommParse(context, UrlConst.BASE_URL).appendRegion(UrlConst.NOTICE_LOCK_CHILD);
        urlParse.putValue("child_id", BabyApplication.getInstance().getCurrentChildId())
                .putValue("lock_screen",lockType)
                .putValue("lock_screen_time",time);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {

                    @Override
                    protected void onSuccess(String data) {

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                    }
                });
    }

    public static void noticePswGames(Context context,int lockType,int time,String psw){
        UrlParse urlParse = new UrlCommParse(context, UrlConst.BASE_URL).appendRegion(UrlConst.NOTICE_PSW_GAME);
        urlParse.putValue("user_id", BabyApplication.getInstance().getCurrentUseId())
                .putValue("temporary_password_lock",lockType)
                .putValue("temporary_password_time",time)
                .putValue("temporary_password",psw);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {

                    @Override
                    protected void onSuccess(String data) {

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                    }
                });
    }

    public static int getWhiteCount(List<AppInfo> appInfoList){
        if(ToolUtils.isListEmpty(appInfoList)){
            return 0;
        }

        int count = 0;
        for (AppInfo appInfo : appInfoList){
            if(containPackage(true,appInfo.getPackageName())){
                count++;
            }
        }

        return count;
    }

    public static void addPackage(boolean isWhite,String packageName){
        if(TextUtils.isEmpty(packageName)){
            return;
        }

        String packJson;
        JSONArray jsonArray = null;
        if(isWhite){
            packJson = SharedPreferencesUtils.getStringDate(Constants.WHITE_JSON_SHAREPREFERS_KEY);
        }else {
            packJson = SharedPreferencesUtils.getStringDate(Constants.BLACK_JSON_SHAREPREFERS_KEY);
        }

        if(TextUtils.isEmpty(packJson)){
            jsonArray = new JSONArray();

        }else {
            try {
                jsonArray = new JSONArray(packJson);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if(jsonArray != null){
            jsonArray.put(packageName);
            packJson = jsonArray.toString();

            if(isWhite){
                SharedPreferencesUtils.setStringDate(Constants.WHITE_JSON_SHAREPREFERS_KEY,packJson);
            }else {
                SharedPreferencesUtils.setStringDate(Constants.BLACK_JSON_SHAREPREFERS_KEY,packJson);
            }

        }
    }

    public static void deletePackage(boolean isWhite,String packageName){
        if(TextUtils.isEmpty(packageName)){
            return;
        }

        String packJson;
        JSONArray jsonArray = null;
        if(isWhite){
            packJson = SharedPreferencesUtils.getStringDate(Constants.WHITE_JSON_SHAREPREFERS_KEY);
        }else {
            packJson = SharedPreferencesUtils.getStringDate(Constants.BLACK_JSON_SHAREPREFERS_KEY);
        }

        if(TextUtils.isEmpty(packJson)){
            jsonArray = new JSONArray();

        }else {
            try {
                jsonArray = new JSONArray(packJson);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if(jsonArray != null){
            for (int i = 0;i < jsonArray.length();i++){
                String pack = jsonArray.optString(i);
                if(pack.equals(packageName)){
                    jsonArray.remove(i);
                }
            }

            if(isWhite){
                SharedPreferencesUtils.setStringDate(Constants.WHITE_JSON_SHAREPREFERS_KEY,jsonArray.toString());
            }else {
                SharedPreferencesUtils.setStringDate(Constants.BLACK_JSON_SHAREPREFERS_KEY,jsonArray.toString());
            }
        }
    }

    public static boolean containPackage(String packageName){
        return containPackage(true,packageName) || containPackage(false,packageName);
    }

    public static boolean containPackage(boolean isWhite,String packageName){
        if(TextUtils.isEmpty(packageName)){
            return false;
        }

        String packJson;
        JSONArray jsonArray = null;
        if(isWhite){
            packJson = SharedPreferencesUtils.getStringDate(Constants.WHITE_JSON_SHAREPREFERS_KEY);
        }else {
            packJson = SharedPreferencesUtils.getStringDate(Constants.BLACK_JSON_SHAREPREFERS_KEY);
        }

        if(TextUtils.isEmpty(packJson)){
            jsonArray = new JSONArray();

        }else {
            try {
                jsonArray = new JSONArray(packJson);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        if(jsonArray != null){
            for (int i = 0;i < jsonArray.length();i++){
                String pack = jsonArray.optString(i);
                if(pack.equals(packageName)){
                    return true;
                }
            }
        }

        return false;
    }

    public static void setTimeAlarm(Context context,boolean isStart,int requestCode,int frequDay,int hour,int min){
        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
        long firstTime = SystemClock.elapsedRealtime(); //获取系统当前时间
        long systemTime = System.currentTimeMillis();

        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); //  这里时区需要设置一下，不然会有8个小时的时间差
        calendar.set(Calendar.MINUTE, min);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        //选择的定时时间
        long selectTime = calendar.getTimeInMillis();
        //  如果当前时间大于设置的时间，那么就从第二天的设定时间开始
        if(systemTime > selectTime) {

            if(isStart && (systemTime > (selectTime + 1000))){
                selectTime = systemTime + 1000;
            }else {
                calendar.add(Calendar.DAY_OF_MONTH, 1);
                selectTime = calendar.getTimeInMillis();
            }
        }

        long time = selectTime - systemTime;// 计算现在时间到设定时间的时间差
        long myTime = firstTime + time;//系统 当前的时间+时间差

        PendingIntent pendingIntent;
        if(isStart){
            Intent intent = new Intent(context, TimeMgLockReceiver.class);
            intent.putExtra("frequDay",frequDay);
            pendingIntent = PendingIntent.getBroadcast(context,requestCode,intent ,PendingIntent.FLAG_CANCEL_CURRENT);
        }else {
            Intent intent = new Intent(context, TimeMgFreeReceiver.class);
            intent.putExtra("frequDay",frequDay);
            pendingIntent = PendingIntent.getBroadcast(context,requestCode,intent,PendingIntent.FLAG_CANCEL_CURRENT);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,myTime,pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,myTime,pendingIntent);
        }
    }

    public static void setTimeMgAlarm(Context context,int requestCode,int frequDay,int startHour,int startMin,int endHour,int endMin){
        setTimeAlarm(context,true,requestCode,frequDay,startHour,startMin);
        setTimeAlarm(context,false,requestCode,frequDay,endHour,endMin);
    }

    public static void cancelTimeMgAlarm(Context context,int requestCode){
        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);
        PendingIntent startPending = PendingIntent.getBroadcast(context,requestCode,
                new Intent(context, TimeMgLockReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(startPending);

        PendingIntent endPending = PendingIntent.getBroadcast(context,requestCode,
                new Intent(context, TimeMgFreeReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(endPending);
    }

    public static void setEyeProjectAlarm(Context context,int workTime){
        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1000,
                new Intent(context, SleepLockReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        long atTimeInMillis = System.currentTimeMillis() + 1000*60*workTime;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC,atTimeInMillis,pendingIntent);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC,atTimeInMillis,pendingIntent);
        }

        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,1000,
                new Intent(context, SleepFreeReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        long atTimeInMillis1 = System.currentTimeMillis() + 1000*60*(workTime + 5);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,atTimeInMillis1,pendingIntent1);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            am.setExact(AlarmManager.RTC_WAKEUP,atTimeInMillis1,pendingIntent1);
        }
    }

    public static void cancelProjectEyeAlarm(Context context){
        AlarmManager am = (AlarmManager)context.getSystemService(ALARM_SERVICE);

        PendingIntent pendingIntent = PendingIntent.getBroadcast(context,1000,
                new Intent(context, SleepLockReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(pendingIntent);

        PendingIntent pendingIntent1 = PendingIntent.getBroadcast(context,1000,
                new Intent(context, SleepFreeReceiver.class),PendingIntent.FLAG_CANCEL_CURRENT);
        am.cancel(pendingIntent1);
    }

    public static boolean isContactsPack(Context context,String packName){
        if(context == null || TextUtils.isEmpty(packName)){
            return false;
        }
        String[] contacts = context.getResources().getStringArray(R.array.contact_pack_name_array);
        for (String contact : contacts){
            if(packName.equals(contact)){
                return true;
            }
        }

        return false;
    }

    public static boolean isMMSPack(Context context,String packName){
        if(context == null || TextUtils.isEmpty(packName)){
            return false;
        }
        String[] mms = context.getResources().getStringArray(R.array.mms_pack_name_array);
        for (String mm : mms){
            if(packName.equals(mm)){
                return true;
            }
        }

        return false;
    }

    public static boolean isInCallUIPack(Context context,String packName){
        if(context == null || TextUtils.isEmpty(packName)){
            return false;
        }
        String[] contacts = context.getResources().getStringArray(R.array.in_call_pack_name_array);
        for (String contact : contacts){
            if(packName.equals(contact)){
                return true;
            }
        }

        return false;
    }

    public static boolean isOpenPack(Context context,String packName){

        if(TextUtils.isEmpty(packName)){
            return false;
        }

        if(isContactsPack(context,packName) || isMMSPack(context,packName) || isInCallUIPack(context,packName)){
            return true;
        }

        return false;
    }

    public static void addGameTime(int min){
        if(min <= 0){
            return;
        }

        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + BabyApplication.getInstance().getCurrentChildId());
        SharedPreferencesUtils.setIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + BabyApplication.getInstance().getCurrentChildId(),gameTime+min);
    }

    public static void delGameTime(int min){
        if(min <= 0){
            return;
        }

        int realTime = 0;
        int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + BabyApplication.getInstance().getCurrentChildId());
        if(gameTime >= min){
            realTime = gameTime - min;
        }
        SharedPreferencesUtils.setIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                + BabyApplication.getInstance().getCurrentChildId(),realTime);
    }

    public static void gotoGamesFloat(final Context context) {
        boolean isChildControl = SharedPreferencesUtils.getBooleanDate(Constants.IS_CHILD_CONTROL_SHAREPREFERS_KEY);
        if(!isChildControl){
            ToastUtils.showToast(context, "请先进入家长模式开启管控");
            return;
        }

        boolean isAllowPlay = SharedPreferencesUtils.getBooleanDates(Constants.ALLOW_PLAY_SWITCH_SHAREPREFERS_KEY);
        if(!isAllowPlay){
            ToastUtils.showToast(context, "允许学习换取娱乐时间的开关已关闭");
            return;
        }

        if(SystemUtils.checkUsagePermission(context) && FloatPermissionUtil.checkPermission(context)){
            BabyApplication shuShanApplication = BabyApplication.getInstance();
            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
            if(baseActivity != null){
                baseActivity.setAllowBack(true);
            }
            ActivityStackManager.getActivityStackManager().popAllActivity();

            GamesFloatWindow gamesFloatWindow = new GamesFloatWindow(shuShanApplication);
            gamesFloatWindow.setPaperId(-2);
            GamesWindowManager.setGamesFloatWindow(gamesFloatWindow);
            GamesWindowManager.createGamesFloatWindow(shuShanApplication);

            //开启玩耍手机时间的闹钟
            int gameTime = SharedPreferencesUtils.getIntDate(Constants.EXIST_GAME_TIME_SHAREPREFERS_KEY
                    + BabyApplication.getInstance().getCurrentChildId());
            ToolUtils.setLockAlarm(context, gameTime);
        }else if(! FloatPermissionUtil.checkPermission(context)){
            new CustomDialog.Builder(context)
                    .setTitle("温馨提示")
                    .setMessage("发现您的手机没有授予悬浮窗权限，请开启后再试")
                    .setNegativeButton("暂不开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    })
                    .setPositiveButton("现在去开启", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
                            if(baseActivity != null){
                                baseActivity.setAllowBack(true);
                            }
                            context.startActivity(new Intent(context, OpenWindowActivity.class));
                        }
                    })
                    .create().show();
        } else if(!SystemUtils.checkUsagePermission(context)){
            new CustomDialog.Builder(context)
                    .setTitle("温馨提示")
                    .setMessage("发现您尚未开启“有权查看应用使用情况”，将导致无法监控小孩玩手机情况，是否去设置？")
                    .setNegativeButton("放弃", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                        }
                    })
                    .setPositiveButton("设置", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();

                            BaseActivity baseActivity = (BaseActivity) ActivityStackManager.getActivityStackManager().currentActivity();
                            if(baseActivity != null){
                                baseActivity.setAllowBack(true);
                            }
                            context.startActivity(new Intent(context, OpenUsageActivity.class));
                        }
                    })
                    .create().show();
        }
    }
}
